package ants.service;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import ants.model.LinkData;

public class BaiduSearchService {	
	public Set<String> getSearchResult(String keyword) {
		Set<String> searchResult = new HashSet<String>();
		try {
			//把传入的字符进行UTF-8编码
			String encodedKeyword = URLEncoder.encode(keyword,"UTF-8");
			//使用Jsoup获取返回的Html文档
			Document doc = Jsoup.connect("http://www.baidu.com/s?wd="+encodedKeyword).get();
			//在文档中得到所有的<a>标签
			Elements aElements = doc.getElementsByTag("a");	
			for (Element element : aElements) {
				if(element.hasAttr("href")) {
					//筛选出<a>标签里class属性为c-showurl的结点
					if(element.attr("class").equals("c-showurl")) {
						String linkData = element.text();
						linkData = linkData.replaceAll("/","^");
						int dash = linkData.indexOf("^");
						if(dash!=-1) {
							linkData = linkData.substring(0,dash).trim();
						}
						
						//System.out.println("url="+linkData);
						//将结点放到返回的String List
						searchResult.add(linkData);
					}					
				}				
			}
			Elements spanElements = doc.getElementsByTag("span");	
			for (Element element : spanElements) {				
				//筛选出<span>标签里class属性为c-showurl的结点
				if(element.attr("class").equals("c-showurl")) {
					String linkData = element.text();
					linkData = linkData.replaceAll(" ","^");
					linkData = linkData.replaceAll("/","^");
					int dash = linkData.indexOf("^");
					if(dash!=-1) {
						linkData = linkData.substring(0,dash).trim();
					}
					//System.out.println("url="+linkData);
					//将结点放到返回的String List
					searchResult.add(linkData);
				}								
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return searchResult;
	}

	
	
}
